package com.changyinBus.common.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {

    public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge); // 1小时
        /*cookie.setHttpOnly(true);
        cookie.setSecure(true);*/
        response.addCookie(cookie);
    }

    public static String getCookie(HttpServletRequest request, String name){
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static Long getCookieByLong(HttpServletRequest request, String name){
        Cookie[] cookies = request.getCookies();
        try{
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (name.equals(cookie.getName())) {
                        return Long.parseLong(cookie.getValue());
                    }
                }
            }
        }catch (Exception e){
            return 0L;
        }
        return 0L;
    }

    public static void deleteCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setPath("/");
        cookie.setMaxAge(0); // 1小时
        /*cookie.setHttpOnly(true);
        cookie.setSecure(true);*/
        response.addCookie(cookie);
    }
}
